<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工个人主页</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- 自定义CSS -->
    <style>
        .user-info {
            color: #337ab7 !important;
        }

        body {
            background-color: #f8f9fa;
            padding: 20px;
        }

        .function-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-top: 20px;
        }

        .function-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            height: 160px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            cursor: pointer;
            padding: 20px;
        }

        .function-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .function-card i {
            font-size: 2.5rem;
            margin-bottom: 15px;
        }

        .function-card h5 {
            margin-bottom: 5px;
            font-weight: 600;
            font-size: 1.2rem;
        }

        .function-card p {
            color: #6c757d;
            font-size: 0.95rem;
            margin-bottom: 0;
        }

        /* 右侧任务进度区域 */
        .progress-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 20px;
            height: calc(100vh - 40px);
            overflow-y: auto;
        }

        .progress-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .progress-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .progress-item {
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }

        .progress-title {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            align-items: center;
        }

        .progress-bar-container {
            height: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
            margin-bottom: 5px;
        }

        .progress-details {
            display: flex;
            justify-content: space-between;
            font-size: 0.85rem;
            color: #6c757d;
        }

        /* 不同功能的颜色 */
        #join-project {
            background-color: #e3f2fd;
            color: #0d47a1;
        }

        #my-tasks {
            background-color: #e8f5e9;
            color: #2e7d32;
        }

        #report-progress {
            background-color: #fff3e0;
            color: #e65100;
            grid-column: span 2;
        }

        .refresh-btn {
            border: none;
            background-color: transparent;
            color: #0d6efd;
            cursor: pointer;
            font-size: 1rem;
        }

        .refresh-btn:hover {
            color: #0b5ed7;
        }

        .section-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 20px;
        }

        /* 用户信息卡片样式 */
        .user-card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 20px;
        }

        .user-details {
            display: flex;
            align-items: center;
        }

        .user-info-text h4 {
            margin-bottom: 5px;
        }

        .user-info-text p {
            color: #6c757d;
            margin-bottom: 0;
        }

        /* 模态框样式增强 */
.modal-content {
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}

/* Toast样式 */
.toast {
    min-width: 300px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}


    </style>
</head>
<body>
<!-- 顶部导航条 -->
<nav class="navbar navbar-expand-lg navbar-light bg-transparent shadow-sm mb-4" style="margin-top:-20px;margin-left:-20px;margin-right:-20px">
    <div class="container-fluid" style="max-height: 35px;">
        <a class="navbar-brand" href="/fine-se">
                <strong>
                    <i style="font-size: 36px; margin-left: 30px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: 700;">
                        <font color="black">Fine</font>
                        <font color="black"> - </font>
                        <font color="#00B0F0">SE</font>
                    </i>
                </strong>
            </a>

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent"
            aria-controls="navbarContent" aria-expanded="false" aria-label="切换导航">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse justify-content-end" id="navbarContent">
            <ul class="navbar-nav mb-2 mb-lg-0">

                <!-- 项目下拉列表 -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle user-info" href="#" id="projectDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-tasks fa-fw"></i>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="projectDropdown" style="min-width: 300px;">
                        <li>
                            <a class="dropdown-item">
                                <div class="d-flex justify-content-between">
                                    <strong>项目1</strong><small class="text-muted">40%</small>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-success" role="progressbar" style="width: 40%;"></div>
                                </div>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <a class="dropdown-item">
                                <div class="d-flex justify-content-between">
                                    <strong>项目2</strong><small class="text-muted">20%</small>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-info" role="progressbar" style="width: 20%;"></div>
                                </div>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <a class="dropdown-item">
                                <div class="d-flex justify-content-between">
                                    <strong>项目3</strong><small class="text-muted">60%</small>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-warning" role="progressbar" style="width: 60%;"></div>
                                </div>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <a class="dropdown-item">
                                <div class="d-flex justify-content-between">
                                    <strong>项目4</strong><small class="text-muted">80%</small>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-danger" role="progressbar" style="width: 80%;"></div>
                                </div>
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-center" href="#"><strong>查看所有项目 <i class="fas fa-angle-right"></i></strong></a></li>
                    </ul>
                </li>

                <!-- 用户信息下拉 -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle user-info" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" style="font-size: 16px;font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
                        <i class="fa fa-user fa-fw"></i> {{ user_full_name }}
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="#"><i class="fas fa-user-circle me-2"></i>用户信息</a></li>
                        <li><a class="dropdown-item" href="#"><i class="fas fa-cog me-2"></i>设置</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="/logout"><i class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 左侧功能区域 - 8/12宽度 -->
            <div class="col-md-8">
                <!-- 用户信息卡片 -->
                <div class="user-card">
                    <div class="user-details">
                        <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="用户头像" class="user-avatar">
                        <div class="user-info-text">
                            <h4>{{user_full_name}}</h4>
                            <p><i class="fas fa-briefcase"></i> 开发工程师 | <i class="fas fa-building"></i> 研发部</p>
                            <p><i class="fas fa-envelope"></i> {{ user_email }} | </p>
                        </div>
                    </div>
                </div>

                <h4 class="section-title"><i class="bi bi-grid"></i> 我的工作台</h4>

                <div class="function-grid">
                    <div class="function-card" id="join-project" style="grid-column: span 2;">
                        <div class="text-center">
                            <i class="fas fa-project-diagram"></i>
                            <h5>加入项目</h5>
                            <p>申请加入新项目</p>
                        </div>
                    </div>

                    <div class="function-card" id="report-progress">
                        <div class="text-center">
                            <i class="fas fa-tasks"></i>
                            <h5>汇报进度</h5>
                            <p>向项目经理汇报工作进展</p>
                        </div>
                    </div>

<!--                    <div class="function-card" id="report-progress">-->
<!--                        <div class="text-center">-->
<!--                            <i class="fas fa-chart-line"></i>-->
<!--                            <h5>汇报进度</h5>-->
<!--                            <p>向项目经理汇报工作进展</p>-->
<!--                        </div>-->
<!--                    </div>-->
                </div>

            </div>

            <!-- 右侧任务进度区域 - 4/12宽度 -->
            <div class="col-md-4">
                <div class="progress-container">
                    <div class="progress-header d-flex justify-content-between align-items-center">
                        <h4 class="section-title"><i class="bi bi-list-check"></i> 我的任务</h4>
                        <button class="refresh-btn" id="refresh-tasks" onclick="window.location.href='/worker'">
                            <i class="bi bi-arrow-clockwise"></i> 刷新
                        </button>
                    </div>

                    <div id="task-progress">
                        <!-- 这里将通过JavaScript动态加载任务进度数据 -->
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-3">正在加载任务数据...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="inviteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">加入项目</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="inviteForm">
                    <div class="mb-3">
                        <label for="inviteCode" class="form-label">请输入邀请码</label>
                        <input type="text" class="form-control" id="inviteCode" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" form="inviteForm" class="btn btn-primary">加入项目</button>
            </div>
        </div>
    </div>
</div>

<!-- 操作结果Toast提示 -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 1100">
    <div id="resultToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <strong class="me-auto">系统提示</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>
</div>

<div class="modal fade" id="reportProgressModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">汇报项目进度</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="reportProgressForm">
                    <div class="mb-3">
                        <label for="subprojectId" class="form-label">请输入子任务ID</label>
                        <input type="number" class="form-control" id="subprojectId" required
                               placeholder="例如：12">
                        <div class="invalid-feedback">请输入有效的子任务ID</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" form="reportProgressForm" class="btn btn-primary">签到该任务</button>
            </div>
        </div>
    </div>
</div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- 自定义JavaScript -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        window.quickReportProgress = function(subprojectId, buttonElement) {
            const toast = new bootstrap.Toast(document.getElementById('resultToast'));
            const csrfToken = getCookie('csrftoken');

            buttonElement.disabled = true;
            buttonElement.innerHTML = '<i class="bi bi-hourglass"></i> 处理中...';

            document.getElementById('toastMessage').innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    正在提交签到请求...
                </div>
            `;
            toast.show();

            fetch('/worker/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    action: 'report_progress',
                    subproject_id: subprojectId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showToast('签到成功！', 'success');
                    document.getElementById('refresh-tasks').click();
                } else {
                    showToast(data.message || '签到失败', 'danger');
                    buttonElement.disabled = false;
                    buttonElement.innerHTML = '<i class="bi bi-check-circle"></i> 签到';
                }
            })
            .catch(error => {
                showToast('请求失败: ' + error, 'danger');
                buttonElement.disabled = false;
                buttonElement.innerHTML = '<i class="bi bi-check-circle"></i> 签到';
            });
        };

        // 2. 任务管理功能
        function fetchTasks() {
            return new Promise((resolve) => {
                try {
                    // 解析Django传递的JSON数据
                    const projectData = JSON.parse('{{ project_data|escapejs }}');

                    const tasks = [];
                    projectData.forEach(project => {
                        tasks.push({
                            id: project.project_id,
                            name: project.project_name,
                            progress: project.project_progress,  // 使用视图函数计算的进度
                            created_at: project.created_at,
                            status: getProjectStatus(project.project_progress),  // 根据进度获取状态
                            project: project.project_name,
                            isProject: true,
                            subprojects: project.subprojects.map(sp => ({
                                id: sp.subproject_id,
                                content: sp.subproject_content,
                                progress: sp.subproject_progress  // 使用子任务实际进度
                            }))
                        });
                    });
                    resolve(tasks);
                } catch (error) {
                    console.error("解析项目数据错误:", error);
                    resolve([]);  // 返回空数组避免页面崩溃
                }
            });
        }

        function getProjectStatus(progress) {
            if (progress >= 100) return "已完成";
            if (progress >= 70) return "进展顺利";
            if (progress >= 30) return "进行中";
            if (progress > 0) return "刚开始";
            return "未开始";
        }

        function renderTasks(tasks) {
        const container = document.getElementById('task-progress');

        if (!tasks.length) {
            container.innerHTML = `
                <div class="text-center py-5">
                    <i class="bi bi-inbox" style="font-size: 2rem;"></i>
                    <p class="mt-3">当前没有任务</p>
                </div>
            `;
            return;
        }

        let html = '<div class="progress-list">';
        tasks.forEach(task => {
        let progressClass = 'bg-primary';
        if (task.progress === 100) progressClass = 'bg-success';
        else if (task.progress < 30) progressClass = 'bg-warning';

        html += `
            <div class="progress-item">
                <div class="progress-title">
                    <strong>${task.name}</strong>
                    <span class="badge bg-light text-dark">
                        <i class="bi ${task.progress === 100 ? 'bi-check-circle-fill text-success' : 'bi-hourglass'}"></i>
                        ${task.status}
                    </span>
                </div>
                <small class="text-muted d-block mb-2">
                    <i class="bi bi-calendar"></i> 创建于: ${task.created_at}
                </small>
                <div class="progress">
                    <div class="progress-bar ${progressClass}"
                        role="progressbar"
                        style="width: ${task.progress}%;"
                        aria-valuenow="${task.progress}"
                        aria-valuemin="0"
                        aria-valuemax="100">
                    </div>
                </div>
                <div class="progress-details">
                    <span>${task.progress}% 完成</span>
                </div>
        `;

        // 添加子任务下拉列表
        if (task.subprojects && task.subprojects.length) {
            html += `
                <div class="mt-3">
                    <button class="btn btn-sm btn-outline-secondary w-100" type="button"
                            data-bs-toggle="collapse"
                            data-bs-target="#subprojects-${task.id}"
                            aria-expanded="false"
                            aria-controls="subprojects-${task.id}">
                        <i class="bi bi-chevron-down"></i> 查看子任务 (${task.subprojects.length})
                    </button>
                    <div class="collapse mt-2" id="subprojects-${task.id}">
                        <div class="list-group">
            `;

            task.subprojects.forEach(subproject => {
                let subProgressClass = 'bg-info';
                if (subproject.progress === 100) subProgressClass = 'bg-success';
                else if (subproject.progress < 30) subProgressClass = 'bg-warning';

                html += `
                    <div class="list-group-item">
                        <div class="d-flex w-100 justify-content-between">
                            <h6 class="mb-1">${subproject.content}</h6>
                            <div>
                                <small>#${subproject.id}</small>
                                ${subproject.progress === 100 ?
                                    '<button class="btn btn-sm btn-outline-success ms-2" disabled><i class="bi bi-check-circle"></i></button>' :
                                    '<button class="btn btn-sm btn-outline-primary ms-2" onclick="quickReportProgress(' + subproject.id + ', this)">' + '<i class="bi bi-check-circle"></i> 签到</button>'}
                            </div>
                        </div>
                        <div class="progress mt-2" style="height: 5px;">
                            <div class="progress-bar ${subProgressClass}"
                                 role="progressbar"
                                 style="width: ${subproject.progress}%;">
                            </div>
                        </div>
                        <div class="d-flex justify-content-between mt-1">
                            <small class="text-muted">
                                <i class="bi bi-percent"></i> ${subproject.progress}% 完成
                            </small>
                            ${subproject.progress === 100 ?
                                '<span class="badge bg-success">已完成</span>' :
                                '<span class="badge bg-primary">进行中</span>'}
                        </div>
                    </div>
                `;
            });

            html += `
                        </div>
                    </div>
                </div>
            `;
        }

        html += `</div>`; // 关闭progress-item
    });
    container.innerHTML = html + '</div>';
}


        // 初始化任务列表
        fetchTasks().then(renderTasks);

        // 3. 加入项目功能
        document.getElementById('join-project').addEventListener('click', function(e) {
            e.preventDefault();
            new bootstrap.Modal(document.getElementById('inviteModal')).show();
            document.getElementById('inviteForm').reset();
        });

        document.getElementById('inviteForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const inviteCode = document.getElementById('inviteCode').value.trim();

            if (!inviteCode) {
                showToast('请输入有效的邀请码', 'warning');
                return;
            }

            joinProject(inviteCode);
        });

        function joinProject(inviteCode) {
            const toast = new bootstrap.Toast(document.getElementById('resultToast'));
            const csrfToken = getCookie('csrftoken');

            document.getElementById('toastMessage').innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    正在加入项目...
                </div>
            `;
            toast.show();

            fetch('/join_project/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({ invite_code: inviteCode })
            })
            .then(response => response.json())
            .then(data => {
                bootstrap.Modal.getInstance(document.getElementById('inviteModal')).hide();
                showToast(data.status === 'success' ? '已成功加入项目！' : data.message || '加入项目失败',
                         data.status === 'success' ? 'success' : 'danger');
            })
            .catch(error => {
                showToast('请求失败: ' + error, 'danger');
            });
        }

        // 4. 辅助函数
        function showToast(message, type = 'info') {
            const toast = document.getElementById('resultToast');
            const toastMessage = document.getElementById('toastMessage');

            toast.className = `toast ${type === 'success' ? 'bg-success text-white' :
                              type === 'danger' ? 'bg-danger text-white' :
                              type === 'warning' ? 'bg-warning text-dark' : ''}`;

            toastMessage.textContent = message;
            new bootstrap.Toast(toast).show();
        }

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 5. 初始化任务列表
        fetchTasks().then(renderTasks);



        // 7. 其他功能卡片点击事件（保留原有跳转功能）
        document.querySelectorAll('.function-card:not(#join-project)').forEach(card => {
            card.addEventListener('click', function() {
                window.location.href = this.getAttribute('onclick').match(/window\.location\.href='([^']+)'/)[1];
            });
        });


                // 3. 汇报进度功能
        document.getElementById('report-progress').addEventListener('click', function(e) {
            e.preventDefault();
            const modal = new bootstrap.Modal(document.getElementById('reportProgressModal'));
            modal.show();
            document.getElementById('reportProgressForm').reset();
        });

        document.getElementById('reportProgressForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const subprojectId = document.getElementById('subprojectId').value.trim();

            if (!subprojectId) {
                document.getElementById('subprojectId').classList.add('is-invalid');
                showToast('请输入有效的子任务ID', 'warning');
                return;
            }

            reportProgress(subprojectId);
        });

        function reportProgress(subprojectId) {
            const toast = new bootstrap.Toast(document.getElementById('resultToast'));
            const csrfToken = getCookie('csrftoken');

            document.getElementById('toastMessage').innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                    正在提交进度报告...
                </div>
            `;
            toast.show();

            fetch('/worker/', {  // 提交到当前页面
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    action: 'report_progress',
                    subproject_id: subprojectId
                })
            })
            .then(response => response.json())
            .then(data => {
                bootstrap.Modal.getInstance(document.getElementById('reportProgressModal')).hide();
                if (data.status === 'success') {
                    showToast('进度报告提交成功！', 'success');
                    // 刷新任务列表
                    document.getElementById('refresh-tasks').click();
                } else {
                    showToast(data.message || '提交失败', 'danger');
                }
            })
            .catch(error => {
                showToast('请求失败: ' + error, 'danger');
            });
        }


    });
</script>
</body>
</html>